package cn.xerllent.system.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.xerllent.common.annotation.AnonymousAccess;
import cn.xerllent.common.annotation.ForbidSubmit;
import cn.xerllent.common.annotation.Log;
import cn.xerllent.common.entity.vo.ResultData;
import cn.xerllent.common.utils.SecurityUtils;
import cn.xerllent.system.service.LogService;
import cn.xerllent.system.service.dto.LogFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 */
@RestController
@RequestMapping("/api/log")
@Api(tags = "监控：日志管理")
@SuppressWarnings("unchecked")
public class LogController {

    private final LogService logService;

    public LogController(LogService logService) {
        this.logService = logService;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    //@PreAuthorize("@el.check('Admin','log:list')")
    public void download(HttpServletResponse response, LogFilter filter) throws IOException {
        filter.setLogtype("INFO");
        logService.download(logService.queryAll(filter), response);
    }

    @Log("导出错误数据")
    @ApiOperation("导出错误数据")
    @GetMapping(value = "/error/download")
    @PreAuthorize("@el.check('Admin','log:list')")
    public void errorDownload(HttpServletResponse response, LogFilter filter) throws IOException {
        filter.setLogtype("ERROR");
        logService.download(logService.queryAll(filter), response);
    }

    @GetMapping
    @ApiOperation("日志查询")
    @PreAuthorize("@el.check('Admin','log:list')")
    public ResponseEntity<Object> getLogs(LogFilter filter, @PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable) {
        filter.setLogtype("INFO");
        //filter.setType(0);
        return new ResponseEntity<>(ResultData.data(logService.queryAll(filter, pageable)), HttpStatus.OK);
    }

    @GetMapping(value = "/mlogs")
    @PreAuthorize("@el.check('Admin','log:list')")
    public ResponseEntity<Object> getApiLogs(LogFilter filter, @PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable) {
        filter.setLogtype("INFO");
        //filter.setType(1);
        return new ResponseEntity<>(ResultData.data(logService.findAllByPageable(filter.getBlurry(), pageable)), HttpStatus.OK);
    }

    @GetMapping(value = "/user")
    @ApiOperation("用户日志查询")
    public ResponseEntity<Object> getUserLogs(LogFilter filter, @PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable) {
        filter.setLogtype("INFO");
        filter.setUsername(SecurityUtils.getUsername());
        return new ResponseEntity<>(ResultData.data(logService.queryAll(filter, pageable)), HttpStatus.OK);
    }

    @GetMapping(value = "/error")
    @ApiOperation("错误日志查询")
    @PreAuthorize("@el.check('Admin','logError:list')")
    public ResponseEntity<Object> getErrorLogs(LogFilter filter, @PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable) {
        filter.setLogtype("ERROR");
        return new ResponseEntity<>(ResultData.data(logService.queryAll(filter, pageable)), HttpStatus.OK);
    }

    @GetMapping(value = "/error/{id}")
    @ApiOperation("日志异常详情查询")
    @PreAuthorize("@el.check('Admin','logError:detail')")
    public ResponseEntity<Object> getErrorLogs(@PathVariable Long id) {
        return new ResponseEntity<>(ResultData.data(logService.findByErrDetail(id)), HttpStatus.OK);
    }
    
    
    @ForbidSubmit
    @DeleteMapping
    @Log("删除所有INFO日志")
    @ApiOperation("删除所有INFO日志")
    @PreAuthorize("@el.check('Admin','logInfo:del')")
    public ResponseEntity<Object> delAllByInfo(@RequestBody Set<Long> ids, @RequestParam(required=false) Integer type) {
    	if(CollectionUtil.isEmpty(ids)) {
    		if(type!=null) {
    			logService.lambdaUpdate().eq(cn.xerllent.system.entity.Log::getType, type).eq(cn.xerllent.system.entity.Log::getLogtype, "INFO").remove();
    		}else {
    			logService.lambdaUpdate().eq(cn.xerllent.system.entity.Log::getLogtype, "INFO").remove();
    		}
    	}else {
    		logService.removeByIds(ids);
    	}
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ForbidSubmit
    @DeleteMapping(value = "/error")
    @Log("删除所有ERROR日志")
    @ApiOperation("删除所有ERROR日志")
    @PreAuthorize("@el.check('Admin','logError:del')")
    public ResponseEntity<Object> delAllByError(@RequestBody Set<Long> ids, @RequestParam(required=false) Integer type) {
    	if(CollectionUtil.isEmpty(ids)) {
    		if(type!=null) {
    			logService.lambdaUpdate().eq(cn.xerllent.system.entity.Log::getType, type).eq(cn.xerllent.system.entity.Log::getLogtype, "ERROR").remove();
    		}else {
    			logService.lambdaUpdate().eq(cn.xerllent.system.entity.Log::getLogtype, "ERROR").remove();
    		}
    	}else {
    		logService.removeByIds(ids);
    	}
        return new ResponseEntity<>(HttpStatus.OK);
    }


}
